package com.sk.weichat.ui.me;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.makeramen.roundedimageview.RoundedImageView;
import com.sk.weichat.R;
import com.sk.weichat.bean.Area;
import com.sk.weichat.bean.EventAvatarUploadSuccess;
import com.sk.weichat.bean.User;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.UserDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.tool.SelectAreaActivity;
import com.sk.weichat.util.CameraUtil;
import com.sk.weichat.util.PermissionUtil;
import com.sk.weichat.util.PickerViewHelper;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.PickerView.TimePickerView;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.view.TipDialog;
import com.sk.weichat.volley.Result;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import org.apache.http.Header;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * 个人信息--编辑资料
 * create by swy 2019-06-24
 */
public class PersonalCenterEditActivity extends BaseActivity implements View.OnClickListener, PermissionUtil.OnRequestPermissionsResultCallbacks {

    private static final int REQUEST_CAMERA_CODE = 1001;
    private static final int REQUEST_CODE_CAPTURE_CROP_PHOTO = 1;
    private static final int REQUEST_CODE_PICK_CROP_PHOTO = 2;
    private static final int REQUEST_CODE_CROP_PHOTO = 3;
    private static final int REQUEST_SET_CITY = 4;//城市
    private static final int REQUEST_SET_NICKNAME = 5;//修改昵称
    private static final int REQUEST_SET_SIGN = 6;//修改个性签名

    private RoundedImageView mImgPhone;
    private Uri mNewPhotoUri;
    private File mCurrentFile;
    private TextView mTvCity;
    private TextView mTvNickname;
    private User mUser;
    private CheckBox mCheckSex;
    private User mTempData;
    private TextView mTvBirthday;
    private TextView mTvSign;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_center_edit);
        initActionBar();
        initView();

    }

    private void initView() {
        mUser=coreManager.getSelf();
        try {
            mTempData = (User) mUser.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        mImgPhone=findViewById(R.id.img_edit_phone);
        mTvNickname=findViewById(R.id.tv_edit_nickname);
        mTvSign=findViewById(R.id.tv_edit_sign);
        mCheckSex=findViewById(R.id.checkbox_center_sex);
        mTvBirthday=findViewById(R.id.tv_edit_birthday);
        mTvCity=findViewById(R.id.tv_edit_city);


        mTvNickname.setText(mUser.getNickName());
        mTvBirthday.setText(TimeUtils.sk_time_s_long_2_str(mUser.getBirthday()));
        mTvCity.setText(Area.getProvinceCityString(mUser.getCityId(), mUser.getAreaId()));
        AvatarHelper.getInstance().displayAvatar(coreManager.getSelf().getNickName(), coreManager.getSelf().getUserId(), mImgPhone, false);
        mTvSign.setText(TextUtils.isEmpty(mUser.getDescription())?getString(R.string.signature_describe_empty):mUser.getDescription());
        if(mUser.getSex()== 0){//小姐姐
            mCheckSex.setChecked(false);
            mCheckSex.setText(getString(R.string.sex_girl));
        }else{//小哥哥
            mCheckSex.setChecked(true);
            mCheckSex.setText(getString(R.string.sex_boy));
        }

        findViewById(R.id.layout_edit_phone).setOnClickListener(this);
        findViewById(R.id.layout_edit_nickname).setOnClickListener(this);
        findViewById(R.id.layout_edit_sign).setOnClickListener(this);
        findViewById(R.id.layout_edit_birthday).setOnClickListener(this);
        findViewById(R.id.layout_edit_city).setOnClickListener(this);

    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.mergerStatus).setBackgroundColor(ContextCompat.getColor(this,R.color.white));
        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText("编辑资料");
        TextView tvRight = (TextView) findViewById(R.id.tv_title_right);
        tvRight.setText("保存");
        tvRight.setTextColor(ContextCompat.getColor(this,R.color.deep_purple));

        findViewById(R.id.iv_title_left).setOnClickListener(this);
        findViewById(R.id.tv_title_right).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            case R.id.iv_title_left://返回
                mUser=coreManager.getSelf();
                if (!mUser.getNickName().equals(mTempData.getNickName())||mUser.getDescription() != mTempData.getDescription()||mUser.getBirthday() != mTempData.getBirthday()
                    ||mUser.getCountryId() != mTempData.getCountryId()||mUser.getProvinceId() != mTempData.getProvinceId()
                    ||mUser.getCityId() != mTempData.getCityId() ||mUser.getAreaId() != mTempData.getAreaId()) {

                    SelectionFrame mSF = new SelectionFrame(this);
                    mSF.setSomething(getString(R.string.dialog_title), "你编辑的资料尚未保存，是否要退出？","退出","保存", new SelectionFrame.OnSelectionFrameClickListener() {
                        @Override
                        public void cancelClick() {
                            finish();
                        }

                        @Override
                        public void confirmClick() {
                            if (TextUtils.isEmpty(mTempData.getNickName())){
                                ToastUtil.showToast(PersonalCenterEditActivity.this,"昵称不能为空");
                                return;
                            }
                            updateData(true);
                        }
                    });
                    mSF.show();
                }else {
                    finish();
                }
                break;

            case R.id.tv_title_right://保存
                updateData(true);
                break;

            case R.id.layout_edit_phone://头像
                showSelectAvatarDialog();
                break;

            case R.id.layout_edit_nickname://昵称
                intent=new Intent(this,SetNicknameActivity.class);
                intent.putExtra("nickname",mTvNickname.getText().toString());
                startActivityForResult(intent,REQUEST_SET_NICKNAME);
                break;

            case R.id.layout_edit_sign://个性签名
                intent=new Intent(this,SetSignActivity.class);
                intent.putExtra("sign",mUser.getDescription());
                startActivityForResult(intent,REQUEST_SET_SIGN);
                break;

            case R.id.layout_edit_birthday://出生年月
                showSelectBirthdayDialog();
                break;

            case R.id.layout_edit_city://家乡
                intent = new Intent(this, SelectAreaActivity.class);
                intent.putExtra(SelectAreaActivity.EXTRA_AREA_TYPE, Area.AREA_TYPE_PROVINCE);
                intent.putExtra(SelectAreaActivity.EXTRA_AREA_PARENT_ID, Area.AREA_DATA_CHINA_ID);
                intent.putExtra(SelectAreaActivity.EXTRA_AREA_DEEP, Area.AREA_TYPE_CITY);
                startActivityForResult(intent, REQUEST_SET_CITY);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_CAPTURE_CROP_PHOTO) {// 拍照返回再去裁减
            if (resultCode == Activity.RESULT_OK) {
                if (mNewPhotoUri != null) {
                    Uri o = mNewPhotoUri;
                    mNewPhotoUri = CameraUtil.getOutputMediaFileUri(this, CameraUtil.MEDIA_TYPE_IMAGE);
                    mCurrentFile = new File(mNewPhotoUri.getPath());
                    CameraUtil.cropImage(this, o, mNewPhotoUri, REQUEST_CODE_CROP_PHOTO, 1, 1, 300, 300);
                } else {
                    ToastUtil.showToast(this, R.string.c_photo_album_failed);
                }
            }
        } else if (requestCode == REQUEST_CODE_PICK_CROP_PHOTO) {// 选择一张图片,然后立即调用裁减
            if (resultCode == Activity.RESULT_OK) {
                if (data != null && data.getData() != null) {
                    Uri o = data.getData();
                    mNewPhotoUri = CameraUtil.getOutputMediaFileUri(this, CameraUtil.MEDIA_TYPE_IMAGE);
                    mCurrentFile = new File(mNewPhotoUri.getPath());
                    CameraUtil.cropImage(this, o, mNewPhotoUri, REQUEST_CODE_CROP_PHOTO, 1, 1, 300, 300);
                } else {
                    ToastUtil.showToast(this, R.string.c_photo_album_failed);
                }
            }
        } else if (requestCode == REQUEST_CODE_CROP_PHOTO) {
            if (resultCode == Activity.RESULT_OK) {
                if (mNewPhotoUri != null) {
                    mCurrentFile = new File(mNewPhotoUri.getPath());
                    AvatarHelper.getInstance().displayUrl(mNewPhotoUri.toString(), mImgPhone);
                    // 上传头像
                    uploadAvatar(mCurrentFile);
                } else {
                    ToastUtil.showToast(this, R.string.c_crop_failed);
                }
            }
        } else if (requestCode == REQUEST_SET_NICKNAME) {// 选择昵称
            if (resultCode == RESULT_OK && data != null) {
                String nickname = data.getStringExtra("nickname");
                mTvNickname.setText(nickname);
                mTempData.setNickName(nickname);
            }
        }else if (requestCode == REQUEST_SET_SIGN) {// 选择个性签名
            if (resultCode == RESULT_OK && data != null) {
                String sign = data.getStringExtra("sign");
                mTvSign.setText(sign);
                mTempData.setDescription(sign);
            }
        }else if (requestCode == REQUEST_SET_CITY) {// 选择城市
            if (resultCode == RESULT_OK && data != null) {
                int countryId = data.getIntExtra(SelectAreaActivity.EXTRA_COUNTRY_ID, 0);
                int provinceId = data.getIntExtra(SelectAreaActivity.EXTRA_PROVINCE_ID, 0);
                int cityId = data.getIntExtra(SelectAreaActivity.EXTRA_CITY_ID, 0);
                int countyId = data.getIntExtra(SelectAreaActivity.EXTRA_COUNTY_ID, 0);

                String province_name = data.getStringExtra(SelectAreaActivity.EXTRA_PROVINCE_NAME);
                String city_name = data.getStringExtra(SelectAreaActivity.EXTRA_CITY_NAME);
                mTvCity.setText(province_name + "-" + city_name);
                mTempData.setCountryId(countryId);
                mTempData.setProvinceId(provinceId);
                mTempData.setCityId(cityId);
                mTempData.setAreaId(countyId);

            }
        } else if (requestCode == REQUEST_CAMERA_CODE) {
            boolean isReadContacts = PermissionUtil.checkSelfPermissions(PersonalCenterEditActivity.this, new String[]{Manifest.permission.CAMERA});
            if (isReadContacts) {
                takePhoto();
            }
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms, boolean isAllGranted) {
        if (isAllGranted) {// 请求权限返回 已全部授权
            takePhoto();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms, boolean isAllDenied) {
        boolean onceAgain = PermissionUtil.deniedRequestPermissionsAgain(this, perms.toArray(new String[perms.size()]));
        if (onceAgain) {
            TipDialog mTipDialog = new TipDialog(this);
            mTipDialog.setmConfirmOnClickListener(getString(R.string.tip_reject_permission_place_holder, getString(R.string.permission_photo)), new TipDialog.ConfirmOnClickListener() {
                @Override
                public void confirm() {
                    PermissionUtil.startApplicationDetailsSettings(PersonalCenterEditActivity.this, REQUEST_CAMERA_CODE);
                }
            });
            mTipDialog.show();
        } else {
            ToastUtil.showToast(PersonalCenterEditActivity.this, getString(R.string.tip_permission_reboot_place_holder, getString(R.string.permission_photo)));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 点击出生年月
     */
    private void showSelectBirthdayDialog() {

        PickerViewHelper.TimePickerViewShow(this, TimePickerView.Type.YEAR_MONTH_DAY,new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                mTempData.setBirthday(TimeUtils.getSpecialBeginTime(date.getTime() / 1000));
                mTvBirthday.setText(PickerViewHelper.getYesMonthDayTime(date));
            }
        });
      /*  Date date = new Date(mTempData.getBirthday() * 1000);
        DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                GregorianCalendar calendar = new GregorianCalendar(year, monthOfYear, dayOfMonth);
                mTempData.setBirthday(TimeUtils.getSpecialBeginTime( calendar.getTime().getTime() / 1000));
                mTvBirthday.setText(TimeUtils.sk_time_s_long_2_str(calendar.getTime().getTime() / 1000));
                long currentTime = System.currentTimeMillis() / 1000;
                long birthdayTime = calendar.getTime().getTime() / 1000;
                if (birthdayTime > currentTime) {
                    ToastUtil.showToast(mContext, R.string.data_of_birth);
                }
            }
        }, date.getYear() + 1900, date.getMonth(), date.getDate());
        dialog.show();*/

    }

    /**
     * 点击头像弹框
     */
    private void showSelectAvatarDialog() {
        String[] items = new String[]{InternationalizationHelper.getString("PHOTOGRAPH"), InternationalizationHelper.getString("ALBUM")};
        AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle(InternationalizationHelper.getString("SELECT_AVATARS"))
                .setSingleChoiceItems(items, -1,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    boolean isReadContacts = PermissionUtil.checkSelfPermissions(PersonalCenterEditActivity.this, new String[]{Manifest.permission.CAMERA});
                                    if (isReadContacts) {
                                        takePhoto();
                                    } else {
                                        PermissionUtil.requestPermissions(PersonalCenterEditActivity.this, 0x01, new String[]{Manifest.permission.CAMERA});
                                    }
                                } else {
                                    selectPhoto();
                                }
                                dialog.dismiss();
                            }
                        });
        builder.show();
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        mNewPhotoUri = CameraUtil.getOutputMediaFileUri(this, CameraUtil.MEDIA_TYPE_IMAGE);
        CameraUtil.captureImage(this, mNewPhotoUri, REQUEST_CODE_CAPTURE_CROP_PHOTO);
    }

    /**
     * 相册选择
     */
    private void selectPhoto() {
        CameraUtil.pickImageSimple(this, REQUEST_CODE_PICK_CROP_PHOTO);
    }

    /**
     * 上传头像
     * @param file
     */
    private void uploadAvatar(File file) {
        if (!file.exists()) {
            // 文件不存在
            return;
        }
        // 显示正在上传的ProgressDialog
        DialogHelper.showDefaulteMessageProgressDialog(this);
        RequestParams params = new RequestParams();
        final String loginUserId = coreManager.getSelf().getUserId();
        params.put("userId", loginUserId);
        try {
            params.put("file1", file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        AsyncHttpClient client = new AsyncHttpClient();
        client.post(coreManager.getConfig().AVATAR_UPLOAD_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
                DialogHelper.dismissProgressDialog();
                boolean success = false;
                if (arg0 == 200) {
                    Result result = null;
                    try {
                        result = JSON.parseObject(new String(arg2), Result.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (result != null && result.getResultCode() == Result.CODE_SUCCESS) {
                        success = true;
                    }
                }

                if (success) {
                    ToastUtil.showToast(PersonalCenterEditActivity.this, R.string.upload_avatar_success);
                    AvatarHelper.getInstance().updateAvatar(loginUserId);// 更新时间
                    EventBus.getDefault().post(new EventAvatarUploadSuccess(true));
                } else {
                    ToastUtil.showToast(PersonalCenterEditActivity.this, R.string.upload_avatar_failed);
                }
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(PersonalCenterEditActivity.this, R.string.upload_avatar_failed);
            }
        });
    }

    /**
     * 更新数据
     */
    private void updateData(boolean flag) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        if (TextUtils.isEmpty(mTempData.getNickName())){
            ToastUtil.showToast(this,"昵称不能为空");
            return;
        }
        if (!mUser.getNickName().equals(mTempData.getNickName())) {
            params.put("nickname", mTempData.getNickName());
        }
        params.put("description", mTempData.getDescription());
        if (mUser.getBirthday() != mTempData.getBirthday()) {
            params.put("birthday", String.valueOf(mTempData.getBirthday()));
        }
        if (mUser.getCountryId() != mTempData.getCountryId()) {
            params.put("countryId", String.valueOf(mTempData.getCountryId()));
        }
        if (mUser.getProvinceId() != mTempData.getProvinceId()) {
            params.put("provinceId", String.valueOf(mTempData.getProvinceId()));
        }
        if (mUser.getCityId() != mTempData.getCityId()) {
            params.put("cityId", String.valueOf(mTempData.getCityId()));
        }
        if (mUser.getAreaId() != mTempData.getAreaId()) {
            params.put("areaId", String.valueOf(mTempData.getAreaId()));
        }

        DialogHelper.showDefaulteMessageProgressDialog(this);
        HttpUtils.get().url(coreManager.getConfig().USER_UPDATE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {
                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if(result.getResultCode()==1){
                            Log.e("lzs","1111");
                            saveLocalData();
                            if(flag){
                                finish();
                            }
                        }else{
                            Log.e("lzs","2222");
                            if (TextUtils.isEmpty(result.getResultMsg())){
                                ToastUtil.showToast(mContext, "保存成功");
                            }else {
                                ToastUtil.showToast(mContext,result.getResultMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(PersonalCenterEditActivity.this);
                    }
                });
    }

    /**
     * 保存本地数据
     */
    private void saveLocalData() {
        if (!mUser.getNickName().equals(mTempData.getNickName())) {
            coreManager.getSelf().setNickName(mTempData.getNickName());
            UserDao.getInstance().updateNickName(mTempData.getUserId(), mTempData.getNickName());     // 更新数据库
        }
        if (mUser.getDescription() != mTempData.getDescription()) {
            coreManager.getSelf().setDescription(mTempData.getDescription());
            UserDao.getInstance().updateDescription(mTempData.getUserId(), mTempData.getDescription() );  // 更新数据库
        }
        if (mUser.getBirthday() != mTempData.getBirthday()) {
            coreManager.getSelf().setBirthday(mTempData.getBirthday());
            UserDao.getInstance().updateBirthday(mTempData.getUserId(), mTempData.getBirthday() + "");// 更新数据库
        }

        if (mUser.getCountryId() != mTempData.getCountryId()) {
            coreManager.getSelf().setCountryId(mTempData.getCountryId());
            UserDao.getInstance().updateCountryId(mTempData.getUserId(), mTempData.getCountryId());
        }
        if (mUser.getProvinceId() != mTempData.getProvinceId()) {
            coreManager.getSelf().setProvinceId(mTempData.getProvinceId());
            UserDao.getInstance().updateProvinceId(mTempData.getUserId(), mTempData.getProvinceId());
        }
        if (mUser.getCityId() != mTempData.getCityId()) {
            coreManager.getSelf().setCityId(mTempData.getCityId());
            UserDao.getInstance().updateCityId(mTempData.getUserId(), mTempData.getCityId());
        }
        if (mUser.getAreaId() != mTempData.getAreaId()) {
            coreManager.getSelf().setAreaId(mTempData.getAreaId());
            UserDao.getInstance().updateAreaId(mTempData.getUserId(), mTempData.getAreaId());
        }

        ToastUtil.showToast(this, "资料保存成功");
//        setResult(RESULT_OK);
//        finish();
    }

}
